package com.hmall.order.listen;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.client.ItemClient;
import com.hmall.client.OrderClient;
import com.hmall.common.pojo.Order;
import com.hmall.common.pojo.OrderDetail;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;


@Component
@Slf4j
public class SpringRabbitListener {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderClient orderClient;
    @Resource
    private ItemClient itemClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue",durable = "true"),
            exchange = @Exchange(name = "delay.direct",delayed = "true"),
            key = "delay"
    ))
    public void listenDelayedQueue(String msg){
        log.info("接收到delay.queue的延迟消息：{}",msg);
        Long orderId = Long.valueOf(msg);

        //根据orderId查询订单信息
        Order order = orderMapper.selectById(orderId);
        //为空直接返回
        if (null == order) {
            return;
        }
        //判断订单status是否为1
        if (1==order.getStatus()){
            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",orderId);
            OrderDetail orderDetail = orderDetailMapper.selectOne(wrapper);
            Integer num = orderDetail.getNum();
            //根据orderId修改订单status为5（取消），注意幂等判断，避免重复消息
            order.setStatus(5);
            order.setEndTime(new Date());
            order.setCloseTime(new Date());
            order.setUpdateTime(new Date());
            orderMapper.updateById(order);
            //调用item-service，根据商品id、商品数量恢复库存
            itemClient.updateByNum(orderDetail.getItemId(),(0-num));
        }
    }

}
